package com.wcfsy.wechat.wx.um.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wcfsy.wechat.wx.exception.ServiceException;
import com.wcfsy.wechat.wx.um.entity.Menu;
import com.wcfsy.wechat.wx.um.entity.TreeNodeVo;
import com.wcfsy.wechat.wx.um.service.IMenuService;
import com.wcfsy.wechat.wx.um.service.IPermissionService;
import com.wcfsy.wechat.wx.util.JsonMessage;

/**
 * 菜单树管理
 * 
 * @author yiqiang
 *
 */
@Controller
@RequestMapping("/cms/menutree_manager")
public class MenuTreeManagerController extends AbstractXssDefenderController {
	private static final Logger logger = LoggerFactory
			.getLogger(MenuTreeManagerController.class);
	@Resource
	private IMenuService menuService;
	@Resource
	private IPermissionService permissionService;

	@RequestMapping({ "/view/page" })
	@ResponseBody
	public ModelAndView mainPage() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("operator/menutree_manager");

		List<Menu> menus = this.menuService.queryTotalMenu();
		List<TreeNodeVo> menuTreeNodeList = new ArrayList<TreeNodeVo>(
				menus == null ? 0 : menus.size());
		TreeNodeVo menuTreeNodeVo = null;
		if ((menus != null) && (!menus.isEmpty())) {
			for (Menu menu : menus) {
				menuTreeNodeVo = new TreeNodeVo();
				menuTreeNodeVo.setId(menu.getId() + "");
				menuTreeNodeVo.setParentId(menu.getParentId() + "");
				menuTreeNodeVo.setName(menu.getText());

				menuTreeNodeList.add(menuTreeNodeVo);
			}
		}

		modelAndView.addObject("menuTreeNodeList", menuTreeNodeList);
		try {
			/*
			 * Subject currentUser = SecurityUtils.getSubject(); if (currentUser
			 * != null) modelAndView.addObject("canDrag",
			 * Boolean.valueOf(currentUser
			 * .isPermitted("menutree_manager:update"))); else
			 */
			modelAndView.addObject("canDrag", Boolean.valueOf(false));
		} catch (Exception e) {
			modelAndView.addObject("canDrag", Boolean.valueOf(false));
			logger.error("菜单树拖拽控制异常，将导致有修改权限的用户无法拖拽菜单：" + e.getMessage());
		}

		return modelAndView;
	}

	@RequestMapping("/add")
	@ResponseBody
	public ModelAndView addMenu(@Param("id") String id,
			@Param("name") String name) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("operator/menutree_manager_add");

		modelAndView.addObject("parentMenuId", id);
		try {
			modelAndView.addObject("parentMenuName",
					URLDecoder.decode(name, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.debug(name + "新增菜单转码异常:" + e.getMessage());
		}
		return modelAndView;
	}

	@RequestMapping({ "/add/submit" })
	@ResponseBody
	public JsonMessage addMenuSubmit(Menu menu) {
		JsonMessage jsonMessage = new JsonMessage();
		if (menu == null) {
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增菜单失败,传入的参数为空");
			return jsonMessage;
		}
		try {
			menu.setPermisCode("notcode");
			if (StringUtils.isBlank(menu.getPermisCode())) {
				jsonMessage.setSuccess("error");
				jsonMessage.setMessage("新增菜单失败:权限代码不能为空");
				return jsonMessage;
			}
			/*Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("code", menu.getPermisCode());
			List<Permission> resultList = this.permissionService
					.findByParam(queryMap);
			if ((resultList == null) || (resultList.isEmpty())) {
				throw new ServiceException("PER001", "权限code不存在");
			}
			if (menu.getParentId() != 0L) {
				Menu parentMenu = this.menuService.getMenuById(menu
						.getParentId());
				if (parentMenu == null) {
					throw new ServiceException("MEU002", "父菜单不存在");
				}
			}*/
			menu.setId(this.menuService.addMenu(menu).longValue());
		} catch (ServiceException e) {
			logger.error("新增菜单失败:" + menu + " 异常：" + e.getCode() + " "
					+ e.getMsg());

			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增菜单失败:" + e.getMsg());
			return jsonMessage;
		} catch (Exception e) {
			logger.error("新增菜单失败:" + menu + " 异常：" + e.getMessage());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增菜单失败:系统异常");
			return jsonMessage;
		}

		jsonMessage.setSuccess("succeed");
		jsonMessage.setMessage("新增菜单成功");

		jsonMessage.setData(menu);

		return jsonMessage;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public JsonMessage deleteMenu(@Param("id") long id) {
		JsonMessage json = new JsonMessage();

		if (this.menuService.getMenuById(id) == null) {
			throw new ServiceException("MEU001", "数据不存在");
		}
		List<Menu> childMenus = this.menuService.queryMenuByParentId(Long
				.valueOf(id));
		if ((childMenus != null) && (!childMenus.isEmpty())) {
			throw new ServiceException("MEU003", "不能删除，存在菜单");
		}
		try {
			this.menuService.deleteMenuById(id);

		} catch (ServiceException e) {
			logger.error("删除菜单失败，id：" + id + " 异常：" + e.getCode() + " "
					+ e.getMsg());
			json.setSuccess("error");
			json.setMessage("删除菜单失败:" + e.getMsg());
			return json;
		} catch (Exception e) {
			logger.error("删除菜单失败，id：" + id + " 异常：" + e.getMessage());
			json.setSuccess("error");
			json.setMessage("删除菜单失败：系统异常");
			return json;
		}
		json.setSuccess("succeed");
		json.setMessage("删除菜单成功");
		return json;
	}

	@RequestMapping("/modify")
	@ResponseBody
	public ModelAndView modifyMenu(@Param("id") long id,
			@Param("parentMenuName") String parentMenuName) {
		ModelAndView modelAndView = new ModelAndView();

		modelAndView.setViewName("operator/menutree_manager_modify");
		try {
			modelAndView.addObject("parentMenuName",
					URLDecoder.decode(parentMenuName, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error("修改菜单编码转化异常：" + e.getMessage());
		}

		Menu menu = this.menuService.getMenuById(id);
		if (menu != null) {
			modelAndView.addObject("menu", menu);
		}
		return modelAndView;
	}

	@RequestMapping("/modify/submit")
	@ResponseBody
	public JsonMessage modifyMenuSubmit(long id, long parentId, String text,
			String url, String permisCode, int enable, String systemCode,
			int menuOrder) {
		JsonMessage jsonMessage = new JsonMessage();
		if (parentId < 0L) {
			parentId = 0L;
		}
		Menu queryMenu = this.menuService.getMenuById(id);
		if (queryMenu == null) {
			throw new ServiceException("MEU001", "数据不存在");
		}
		if ((parentId == queryMenu.getParentId())
				&& (StringUtils.equals(text, queryMenu.getText()))
				&& (StringUtils.equals(url, queryMenu.getUrl()))
				&& (StringUtils.equals(permisCode, queryMenu.getPermisCode())))
			if (((enable == 1) == queryMenu.isEnable())
					&& (StringUtils.equals(systemCode,
							queryMenu.getSystemCode()))
					&& (menuOrder == queryMenu.getMenuOrder())) {
				jsonMessage.setSuccess("succeed");
				jsonMessage.setMessage("更新菜单成功");
				jsonMessage.setData(queryMenu);
				return jsonMessage;
			}
		Menu menu = new Menu();
		try {
			menu.setId(id);
			menu.setParentId(parentId);
			menu.setText(text);
			menu.setUrl(url);
			menu.setPermisCode(permisCode);
			menu.setEnable(enable == 1);
			menu.setSystemCode(systemCode);
			menu.setMenuOrder(menuOrder);

			this.menuService.updateMenu(menu);

		} catch (ServiceException e) {
			logger.error("更新菜单失败, Menu:" + menu + " 异常：" + e.getCode() + " "
					+ e.getMsg());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("更新菜单失败:" + e.getMsg());

			return jsonMessage;
		} catch (Exception e) {
			logger.error("更新菜单失败, Menu:" + menu + " 异常：" + e.getMessage());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("更新菜单失败:系统异常");

			return jsonMessage;
		}
		jsonMessage.setSuccess("succeed");
		jsonMessage.setMessage("更新菜单成功");
		jsonMessage.setData(menu);
		return jsonMessage;
	}

}
